package com.itheima.tlias.utils;


import com.itheima.tlias.properties.JWTProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 创建/解析 jwt
 *
 * @Author mr.luo
 * @Date 12 4月 2025 22:26
 */
@Component
public class JwtUtils {
    @Autowired
    private JWTProperties jwtProperties;
    /**
     * 生成JWT令牌token
     */
    public String createToken(Integer id){
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, jwtProperties.getSecretKey())
                .claim("id", id)
                .setExpiration(new Date(System.currentTimeMillis() + jwtProperties.getExpire()))
                .compact();
        return token;
    }

    /**
     * 解析jwt令牌返回载荷
     */
    public Claims parseJWT(String token) {
        return Jwts.parser()
                .setSigningKey(jwtProperties.getSecretKey())
                .parseClaimsJws(token)
                .getBody();
    }
}
